import { ProColumns, ProTable } from '@ant-design/pro-table';
import { message, Modal } from 'antd';
import React, { PropsWithChildren } from 'react';
import { SearchWordsType } from '@/models/searchWords';
import { updateSearchWords } from '@/services/searchWordsService';

interface UpdateSearchProps {
  oldData: SearchWordsType.SuggestWordsSearchVo;
  modalVisible: boolean;
  columns: ProColumns<SearchWordsType.SuggestWordsSearchVo>[];
  onSubmit: () => void;
  onCancel: () => void;
}

/***
 *  更新数据模型框
 * @param fields
 */
const handleUpdate = async (
  fields: SearchWordsType.SearchWordsUpdateRequest,
) => {
  const hide = message.loading('正在修改');
  try {
    await updateSearchWords({
      ...fields,
    });
    hide();

    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试');
    return false;
  }
};

/***
 *  更新数据模型框
 * @param props
 */
const AdminUpdateSearch: React.FC<PropsWithChildren<UpdateSearchProps>> = (
  props,
) => {
  const { oldData, columns, modalVisible, onSubmit, onCancel } = props;

  return (
    <Modal
      destroyOnClose
      title="更新"
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <ProTable<
        SearchWordsType.SuggestWordsSearchVo,
        SearchWordsType.SearchWordsUpdateRequest
      >
        rowKey="id"
        type="form"
        columns={columns}
        form={{
          initialValues: oldData,
        }}
        onSubmit={async (value) => {
          const success = await handleUpdate({
            ...value,
            id: oldData.id,
            searchCategory: oldData.searchCategory,
          });
          if (success) {
            onSubmit?.();
          }
        }}
      />
    </Modal>
  );
};

export default AdminUpdateSearch;
